import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Timer;
import java.util.TimerTask;

public class L extends JFrame {
    private JTextField timeField;
    private JButton setAlarmButton;
    private JLabel statusLabel;

    public L() {
        // 设置窗口
        setTitle("高级闹钟");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        
        // 创建UI组件
        timeField = new JTextField(10);
        timeField.setToolTipText("请输入时间 (HH:mm:ss)");
        setAlarmButton = new JButton("设置闹钟");
        statusLabel = new JLabel("等待设置闹钟...");
        
        // 添加组件到窗口
        JPanel panel = new JPanel();
        panel.add(new JLabel("闹钟时间:"));
        panel.add(timeField);
        panel.add(setAlarmButton);
        
        add(panel, BorderLayout.CENTER);
        add(statusLabel, BorderLayout.SOUTH);
        
        // 设置按钮事件
        setAlarmButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setAlarm();
            }
        });
    }

    private void setAlarm() {
        String inputTime = timeField.getText().trim();
        
        try {
            // 解析用户输入的时间
            LocalTime alarmTime = LocalTime.parse(inputTime, DateTimeFormatter.ofPattern("HH:mm:ss"));
            LocalTime currentTime = LocalTime.now();
            
            // 计算延迟时间（毫秒）
            long delay = calculateDelay(currentTime, alarmTime);
            
            if (delay < 0) {
                // 如果输入的时间已经过了，自动设置为明天
                delay += 24 * 60 * 60 * 1000;
            }
            
            // 显示闹钟设置成功
            statusLabel.setText("闹钟已设置：" + inputTime);
            
            // 创建定时器任务
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    // 播放自定义音频
                    playSound("alarm.wav");
                    
                    // 显示提醒对话框
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(
                            L.this, 
                            "闹钟时间到！", 
                            "提醒", 
                            JOptionPane.INFORMATION_MESSAGE
                        );
                        statusLabel.setText("等待设置闹钟...");
                    });
                }
            }, delay);
            
        } catch (DateTimeParseException ex) {
            JOptionPane.showMessageDialog(
                this, 
                "时间格式错误，请使用 HH:mm:ss 格式", 
                "错误", 
                JOptionPane.ERROR_MESSAGE
            );
        }
    }

    private long calculateDelay(LocalTime currentTime, LocalTime alarmTime) {
        // 计算两个时间点之间的毫秒差
        long currentMillis = currentTime.toNanoOfDay() / 1_000_000;
        long alarmMillis = alarmTime.toNanoOfDay() / 1_000_000;
        return alarmMillis - currentMillis;
    }

    private void playSound(String soundFilePath) {
        try {
            // 从文件加载音频
            File soundFile = new File(soundFilePath);
            
            // 检查文件是否存在
            if (!soundFile.exists()) {
                throw new IOException("音频文件不存在: " + soundFilePath);
            }
            
            // 获取音频输入流
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundFile);
            
            // 获取剪辑对象并打开音频
            Clip clip = AudioSystem.getClip();
            clip.open(audioInputStream);
            
            // 播放音频
            clip.start();
            
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
            System.err.println("播放音频失败，使用默认提示音: " + e.getMessage());
            // 播放失败时降级使用系统默认提示音
            Toolkit.getDefaultToolkit().beep();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            L alarmClock = new L();
            alarmClock.setVisible(true);
        });
    }
}